package com.yls.except.controller;

import com.yls.except.service.UserService;
import com.yls.except.service.impl.BaseServiceImpl;
import com.yls.except.task.RedisCash;
import com.yls.except.util.RegularHandle.RegularJudge;
import com.yls.except.util.exception.ExceptionHandle;
import com.yls.except.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 用户controller
 * 登录token标识： 3464646365326578636570743339613162333430616462396539633137396239643132656665
 * 代理token：3030333435616578636570743034333366393431373461623366613231316230616566333261
 * 高级用户token:6565366164336578636570743062653631373434356261636534386339393133393234363866
 * 代理用户1：6339383064666578636570743939633762633430613138646437393666623461303539616264
 * 代理用户2：6563663436396578636570743537376562633434643638303030616331653732633734336637
 * 代理用户3：3763386462346578636570743162386462313466393362656361613930633337366263643630
 */
@Controller
@RequestMapping(value = "usercontroller")
public class UserController extends ExceptionHandle {
    @Resource(name = "userService")
    private UserService userService;

    /**
     * 登录
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "userlogin.do")
    public void userLogin(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String json = req.getParameter("json");
        String reqip = IpAddressUitls.getIpAddr(req);
        if (StringIsempty.isallempty(json))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            Map<String, Object> map = GeneralResult.jsonStrToMap(json);
            if (StringIsempty.isNullMap(map))
                GeneralResult.general(resp, list, 20001, 0);
            else {
                String openid = map.get("openid") + "";
                String nickname = map.get("nickname") + "";
                String sex = map.get("sex") + "";
                String head = map.get("head") + "";
                String invitecode = map.get("invitecode") + "";
                if (StringIsempty.isallempty(openid))
                    GeneralResult.general(resp, list, 20001, 0);
                else {
                    Map<String, Object> userinfo = userService.insertUser(openid, nickname, sex, head, reqip, invitecode, "");
                    if (StringIsempty.isNullMap(userinfo))
                        GeneralResult.general(resp, list, 20013, 0);
                    else {
                        setUserCookie(resp, userinfo);

                        userinfo.remove("uid");
                        GeneralResult.generalMap(resp, userinfo);
                    }
                }
            }
        }
    }

    public static void setUserCookie(HttpServletResponse resp, Map<String, Object> userinfo) {
        String item = ImgProperties.getConstan("itemname");
        String token = userinfo.get("token") + "";
        Cookie namecookie = new Cookie("token", token);
        namecookie.setMaxAge(-1);
        namecookie.setPath("/" + item);
        resp.addCookie(namecookie);
        String type = userinfo.get("usertype") + "";
        namecookie = new Cookie("type", type);
        namecookie.setMaxAge(-1);
        namecookie.setPath("/" + item);
        resp.addCookie(namecookie);
        String uid = userinfo.get("uid") + "";
        uid = HexString.insertstr(item, 1, uid);
        uid = HexString.encode(uid);  //加密
        namecookie = new Cookie("invitecode", uid);
        namecookie.setMaxAge(-1);
        namecookie.setPath("/" + item);
    }

    /**
     * 退出
     * @param req
     * @param resp
     */
    @RequestMapping(value = "loginout.action")
    public void loginout(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String loginoutip = IpAddressUitls.getIpAddr(req);
        if (StringIsempty.isallempty(uid)) {
            GeneralResult.general(resp, list, 10001, 0);
        } else {
            String item = ImgProperties.getConstan("itemname");
            Cookie namecookie = new Cookie("token", "");
            namecookie.setMaxAge(0);
            namecookie.setPath("/" + item);
            resp.addCookie(namecookie);
            namecookie = new Cookie("type", "");
            namecookie.setMaxAge(0);
            namecookie.setPath("/" + item);
            resp.addCookie(namecookie);
            uid = HexString.insertstr(item, 1, "");
            uid = HexString.encode(uid);  //加密
            namecookie = new Cookie("invitecode", uid);
            namecookie.setMaxAge(0);
            namecookie.setPath("/" + item);
            resp.addCookie(namecookie);
            int tag = userService.updateLoginOut(uid, loginoutip, 2);
            if (tag > 0) {
                BaseServiceImpl.removeUserTokenByUid(uid);
            }
            GeneralResult.general(resp, list, 20000, 0);
        }
    }

    /**
     * 获取用户个人资料信息
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "getuserinfo.action")
    public void getUserInfo(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else {
            Map<String, Object> user = userService.selectUserInfoByUid(uid);
            GeneralResult.generalMap(resp, user);
        }
    }

    /**
     * 修改用户个人资料
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "edituserinfo.controller")
    public void updateUserInfo(HttpServletRequest req, HttpServletResponse resp, HttpSession session, @RequestParam MultipartFile[] headimg) {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            String json = req.getParameter("json");
            Map<String, Object> map = GeneralResult.jsonStrToMap(json);
            String token = map.get("token") + "";
            List<Object> list = new ArrayList<Object>();
            String item = ImgProperties.getConstan("itemname");
            final String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/";
            if (StringIsempty.isallempty(token)) {
                GeneralResult.general(resp, list, 10001, 0); // 参数有误
            } else {
                token = HexString.decode(token);
                token = HexString.removestr(token, 6, item, "");
                Map<String, String> utokenmap = RedisCash.getMap(token);
                boolean flag = false;
                if (StringIsempty.isNullMap(utokenmap)) {
                    GeneralResult.general(resp, list, 10001, 0); // 未登录
                } else {
                    String uid = utokenmap.get("uid");
                    String type = utokenmap.get("type");
                    long datetime = Long.parseLong(utokenmap.get("time"));
                    long timestamp = new Date().getTime();
                    long mistaketime = timestamp - datetime;
                    double time = mistaketime / 1000 / 60 / 60 / 24;
                    time = Math.abs(time);
                    if (StringIsempty.isallempty(uid) || StringIsempty.isallempty(type))
                        GeneralResult.general(resp, list, 10002, 0);
                    else if (time <= ConstantUtil.LONGTIME) {
                        req.setAttribute("uid", uid);
                        req.setAttribute("type", type);
                        utokenmap.put("time", timestamp + "");
                        RedisCash.redisMap("life" + token, utokenmap);

                        String src = ImgProperties.getimg("headimg");
                        String date = UtilDate.getShijian();
//                            String path = basePath + src + date + filename;
                        String realPath = session.getServletContext().getRealPath(src);
                        String showimg = UploadController.uploadimg(headimg, src, realPath, date, basePath);

                        String birthday = req.getParameter("birthday");
                        String nickname = req.getParameter("nickname");
                        String sex = req.getParameter("sex");
                        int tag = userService.updateUserinfo(uid, showimg, nickname, sex, birthday);
                        GeneralResult.general(resp, list, tag, 1);
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改用户个人资料
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "edituserinfo.action")
    public void editUserInfo(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";  //获取登陆用户id
        String nickname = req.getParameter("nickname");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else {
            int tag = userService.updateUserinfo(uid, "", nickname, sex, birthday);
            GeneralResult.general(resp, list, tag, 1);
        }
    }

    /**
     * 获取验证码与验证验证码
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "getphonecode.action")
    public void getPhoneCode(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";  //获取登陆用户id
        String phone = req.getParameter("phone"); //电话号码
        String type = req.getParameter("type");  //类型 0：绑定手机号  1：设置密码
        String code = req.getParameter("code"); //验证码
        String tag = req.getParameter("tag");  //0：获取验证码  1：判断验证码
        String addip = IpAddressUitls.getIpAddr(req);
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);   //未登录
        else if (StringIsempty.isallempty(phone) || StringIsempty.isallempty(type) || StringIsempty.isallempty(tag))  //验证电话、获取验证码类型和接口类型是否为空
            GeneralResult.general(resp, list, 20001, 0);   //参数有误
        else if (!RegularJudge.isphone(phone))
            GeneralResult.general(resp, list, 20027, 0);   //请输入正确的手机号
        else {
            if ("hq".equals(tag)) {
                if (YzCodeTime.yzcode(phone))   //验证该手机号获取验证码且未使用的验证码是否超过1分钟
                    GeneralResult.general(resp, list, 20003, 0);  //获取验证码过于频繁
                else {
                    int flag = userService.insertPhoneCode(phone, type, uid, addip);    //新增获取短信记录以及发送短信
                    if (flag > 0)
                        list.add(flag);
                    GeneralResult.general(resp, list, flag, 1);
                }
            } else if ("yz".equals(tag)) {
                if (StringIsempty.isallempty(code))  //判断验证码是否为空
                    GeneralResult.general(resp, list, 20001, 0);  //参数有误
                else if (!RegularJudge.isnumber(code))
                    GeneralResult.general(resp, list, 20028, 0);  //验证码格式错误
                else {
                    Map<String, String> phoneyz = RedisCash.getMap(phone);  //根据手机号获取缓存的验证码
                    if (StringIsempty.isNullMap(phoneyz)) {  //判断该验证码是否存在
                        GeneralResult.general(resp, list, 20007, 0); // 验证码超时
                    } else {
                        String yzcode = phoneyz.get("yzcode") + "";  //获取验证码
                        String yztype = phoneyz.get("type") + "";
                        if (StringIsempty.isNullMap(phoneyz))  //判断是否存在该手机号验证码
                            GeneralResult.general(resp, list, 20007, 0);    //验证码超时
                        else if (!code.equals(yzcode) || !type.equals(yztype)) //判断验证码是否正确
                            GeneralResult.general(resp, list, 20008, 0);    //验证码错误
                        else {
                            String itemname = ImgProperties.getConstan("itemname");
                            String typename = "";
                            if ("0".equals(type))
                                typename = ImgProperties.getConstan("threebindingphone");
                            else if ("1".equals(type))
                                typename = ImgProperties.getConstan("forgetpwd");
                            String phonecode = HexString.phoneencode(phone, typename, itemname + code);
                            Map<String, Object> phonemap = new HashMap<String, Object>();
                            phonemap.put("phonecode", phonecode);
                            GeneralResult.generalMap(resp, phonemap, 20000);
                        }
                    }
                }
            } else
                GeneralResult.general(resp, list, 20001, 0);
        }
    }

    /**
     * 绑定手机号
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "bindingphone.action")
    public void bindingPhone(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String phone = req.getParameter("phone");
        String phonecode = req.getParameter("phonecode");
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else if (StringIsempty.isallempty(phone) || StringIsempty.isallempty(phonecode))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            Map<String, String> phoneyz = RedisCash.getMap(phone);  //根据手机号获取缓存的验证码
            if (StringIsempty.isNullMap(phoneyz)) {  //判断该验证码是否存在
                GeneralResult.general(resp, list, 20007, 0); // 验证码超时
            } else {
                String yzcode = phoneyz.get("yzcode") + "";  //获取验证码
                String type = phoneyz.get("type") + "";
                if (!"0".equals(type))
                    GeneralResult.general(resp, list, 20060, 0);
                else {
                    String itemname = ImgProperties.getConstan("itemname");  //获取项目名
                    String typename = ImgProperties.getConstan("threebindingphone");  //获取验证码类型
                    phonecode = HexString.phonedecode(phonecode, typename, itemname + yzcode);  //解密
                    if (!phonecode.equals(phone))
                        GeneralResult.general(resp, list, 20011, 0); // 该手机号和获取验证码的手机号不一致
                    else {
                        int tag = userService.updateBindingPhone(uid, phone);
                        GeneralResult.general(resp, list, tag, 1);
                        if (tag > 0) {//操作成功清除手机验证码
                            //从缓存移除该手机号信息
                            RedisCash.removeKey(phone);
                            RedisCash.removeListKey("exceptlifeyzphone", phone);
                        }
                    }
                }
            }
        }
    }

    /**
     * 设置密码
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "setpwd.action")
    public void setPwd(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String phone = req.getParameter("phone");
        String phonecode = req.getParameter("phonecode");
        String pwd = req.getParameter("userpwd");
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else if (StringIsempty.isallempty(phone) || StringIsempty.isallempty(phonecode) || StringIsempty.isallempty(pwd))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            Map<String, String> phoneyz = RedisCash.getMap(phone);  //根据手机号获取缓存的验证码
            if (StringIsempty.isNullMap(phoneyz)) {  //判断该验证码是否存在
                GeneralResult.general(resp, list, 20007, 0); // 验证码超时
            } else {
                String yzcode = phoneyz.get("yzcode") + "";  //获取验证码
                String type = phoneyz.get("type") + "";
                if (!"1".equals(type))
                    GeneralResult.general(resp, list, 20060, 0);
                else {
                    String itemname = ImgProperties.getConstan("itemname");  //获取项目名
                    String typename = ImgProperties.getConstan("forgetpwd");  //获取验证码类型
                    phonecode = HexString.phonedecode(phonecode, typename, itemname + yzcode);  //解密
                    if (!phonecode.equals(phone))
                        GeneralResult.general(resp, list, 20011, 0); // 该手机号和获取验证码的手机号不一致
                    else {
                        int tag = userService.updateUserPwd(uid, phone, pwd);
                        GeneralResult.general(resp, list, tag, 1);
                        if (tag > 0) {//操作成功清除手机验证码
                            //从缓存移除该手机号信息
                            RedisCash.removeKey(phone);
                            RedisCash.removeListKey("exceptlifeyzphone", phone);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取我的余额
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "getmyspare.action")
    public void getMySpare(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else {
            Map<String, Object> useracountinfo = userService.selectUserAccountByUid(uid);
            GeneralResult.generalMap(resp, useracountinfo);
        }
    }

    /**
     * 获取我的代理
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "inviteinfo.action")
    public void inviteInfo(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String page = req.getParameter("page");
        String type = req.getAttribute("type") + "";
        if (StringIsempty.isallempty(uid) || StringIsempty.isallempty(type))
            GeneralResult.general(resp, list, 10001, 0);
        else {
            list = userService.selectInviteInfoByUid(uid, page);
            GeneralResult.resultList(list, resp);
        }
    }

    /**
     * 获取用户认证信息
     * @param req
     * @param resp
     */
    @RequestMapping(value = "getuserauth.action")
    public void getUserAuth(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        if(StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else {
            Map<String, Object> auth = userService.selectUserAuthInfoByUId(uid);
            GeneralResult.generalMap(resp, auth);
        }
    }

    /**
     * 实名认真申请
     * @param req
     * @param resp
     */
    @RequestMapping(value = "authapply.action")
    public void authApply(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String name = req.getParameter("name");
        String card = req.getParameter("card");
        String reqip = IpAddressUitls.getIpAddr(req);
        if(StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else if(StringIsempty.isallempty(name) || StringIsempty.isallempty(card))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            int tag = userService.insertUserAuth(uid, name, card, reqip);
            GeneralResult.general(resp, list, tag, 1);
        }
    }

    /**
     * 获取代理价格信息
     * @param req
     * @param resp
     */
    @RequestMapping(value = "getUserProxyInfo.action")
    public void getUserProxyInfo(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getAttribute("uid") + "";
        if(StringIsempty.isallempty(uid))
            GeneralResult.general(resp, null, 10001, 0);
        else {
            Map<String, Object> userproxy = userService.selectUserProxyInfoByUId(uid);
            GeneralResult.generalMap(resp, userproxy);
        }

    }

    public static void main(String[] args) {
//        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//        map.put(1,1);
//        map.put(2,21);
//        map.put(3,3);
//        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
//
//            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//
//        }
        String str = "asdfasd''\"";
        str = str.replaceAll("'", "").replaceAll("\"", "");
        System.out.println(str);
    }
}